package com.yusvn.scm.admin.service;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.yusvn.scm.common.BaseService;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.SysMenu;

/**
 * 菜单管理
 * @author liugz
 *
 */
public class AdminMenuService extends BaseService {

	private SysMenu dao = new SysMenu().dao();
	
	public List<SysMenu> list() {
		return dao.findAll();
	}
	
	public RetKit add(String jsonObj) {
		SysMenu menu = JSON.parseObject(jsonObj, SysMenu.class);
		
		menu.setTitle(menu.getTitle().trim());
		
		if(menu.save()) {
			return RetKit.ok("添加成功");
		}
		
		return RetKit.fail("添加失败");
	}

	public RetKit update(String jsonObj) {
		SysMenu menu = JSON.parseObject(jsonObj, SysMenu.class);
		
		menu.setTitle(menu.getTitle().trim());
		
		if(menu.update()) {
			return RetKit.ok("修改成功");
		}
		
		return RetKit.fail("修改失败");
	}

	public RetKit remove(String id) {
		if(dao.deleteById(id)) {
			return RetKit.ok("删除成功");
		}
		return RetKit.fail("删除失败");
	}
	
	/**
	 * 获取菜单数据
	 */
	public List<SysMenu>  getUserMenu(Integer userId, Integer menuType) {
		
		List<SysMenu> list = dao.find("SELECT DISTINCT b.* FROM sys_role_menu a " + 
				"LEFT JOIN sys_menu b ON a.menu_id = b.menu_id " + 
				"LEFT JOIN sys_role c ON a.role_id = c.role_id " + 
				"WHERE a.role_id IN ( SELECT role_id FROM sys_user_role WHERE user_id=? ) " + 
				"AND b.deleted = 0 AND c.deleted=0 " +
				"AND b.menu_type=? " + 
				"ORDER BY b.sort_number ", 
				userId, menuType);
		
		return list;
	}
	
	/**
	 * 组装成菜单树
	 */
	public List<SysMenu> toMenuTree(List<SysMenu> menus, Integer parentId) {
		List<SysMenu> list = new ArrayList<>();
        for (SysMenu menu : menus) {
        	if (parentId.equals(menu.getParentId())) {
        		menu.setChildren(toMenuTree(menus, menu.getMenuId()));
        		
                list.add(menu);
            }
        }
        return list;
	}
	
	/**
	 * 获取用户权限
	 */
	public List<SysMenu> getUserMenu(Integer userId) {
		
		List<SysMenu> list = dao.find("SELECT DISTINCT b.* FROM sys_role_menu a " + 
				"LEFT JOIN sys_menu b ON a.menu_id = b.menu_id " + 
				"LEFT JOIN sys_role c ON a.role_id = c.role_id " + 
				"WHERE a.role_id IN ( SELECT role_id FROM sys_user_role WHERE user_id=? ) " + 
				"AND b.deleted = 0 AND c.deleted=0 " +
				//"AND b.menu_type=? " + 
				"ORDER BY b.sort_number ", 
				userId);
		
		return list;
	}
	
}
